package com.xander.utils;

import com.xander.entity.Link;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;

/**
 * Created by YE on 2018/5/3.
 */
public class LinkUtils {

    //将url字符串转成link类
    public static Link formatUrl(String url) {
        String deurl = null;
        Link link = null;
        try {
            if (url.length() >= 15 && url.substring(0, 15).equals("https://url.cn/")) {
                url = getRedirectUrl(url);
            }
            try {
                deurl = URLDecoder.decode(url, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            String[] s = deurl.split("&");
            int number = 0;
            int platform = 0;
            String sn = null;
            //分割url得到数据
            for (String str : s) {
                if (str.length() >= 12 && str.substring(0, 12).equals("lucky_number")) {
                    number = Integer.parseInt(str.split("=")[1]);
                }
                if (str.length() >= 8 && str.substring(0, 8).equals("platform")) {
                    platform = Integer.parseInt(str.split("=")[1]);
                }
                if (str.length() >= 2 && str.substring(0, 2).equals("sn")) {
                    sn = str.split("=")[1];
                }
            }
            if(sn!=null){
                link = new Link();
                link.setSn(sn);
                link.setLuckynumber(number);
                link.setPlatform(platform);
                link.setLinkurl(url);
            }

        } catch (Exception e) {
            link = null;
        }
        return link;
    }

    //短链接重定向
    public static String getRedirectUrl(String url) {
        HttpURLConnection conn = null;
        try {
            conn = (HttpURLConnection) new URL(url).openConnection();
            conn.setInstanceFollowRedirects(false);
            conn.setConnectTimeout(5000);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return conn.getHeaderField("Location");
    }

}
